/*
 * BattlePetResource.cpp
 *
 *  Created on: 2013. 11. 5.
 *      Author: mega@gamevil.com
 */

#include <Database/Static.h>
#include <Logger/Static.h>

#include "../macro.h"
#include "../NUtil/Pool.h"
#include "Static.h"
#include "BattlePetResource.h"

namespace ProjectZ { namespace NResource {

BattlePetResource::BattlePetResource()
{

}

BattlePetResource::~BattlePetResource()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<BATTLEPETTREE::value_type>);
}

void BattlePetResource::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<BATTLEPETTREE::value_type>);
	clsFlyTree.clear();
}

bool
BattlePetResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT * FROM resource_battlepet");

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if (clsAuto->GetErrorIdx() != 0)
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while (clsAuto->Next())
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		Toolkit::Str<30> BATTLEPET_TYPE;
		Toolkit::Str<10> BATTLEPET_VER;

		Flyweight * pFly = new Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_CHAR_TID >> pFly->_ITEM_TID >> BATTLEPET_TYPE
				>> pFly->_PET_DGREE >> BATTLEPET_VER >> pFly->_PET_OPEN_LEVEL;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		int value = 0;
		bool bRet = Static::Instance().GetStringMatch()->GetValue(BATTLEPET_TYPE.c_str(), value);
		if (bRet == false)
		{
			DEBUGLOG("BATTLEPET RESOURCE BATTLEPET_TYPE : %s VALUE : %d", BATTLEPET_TYPE.c_str(), value);
			return false;
		}
		pFly->_BATTLE_TYPE = value;

		value = 0;
		bRet = Static::Instance().GetStringMatch()->GetValue(BATTLEPET_VER.c_str(), value);
		if (bRet == false)
		{
			DEBUGLOG("BATTLEPET RESOURCE BATTLEPET_VER : %s VALUE : %d", BATTLEPET_VER.c_str(), value);
			return false;
		}
		pFly->_PET_VERSION = value;

		clsFlyTree[Key(pFly->_CHAR_TID, pFly->_ITEM_TID)] = pFly;
	}

	return true;
}

BattlePetResource::Flyweight *
BattlePetResource::GetFly(BattlePetResource::Key & clsKey)
{
	auto iter = clsFlyTree.find(clsKey);
	if (iter == clsFlyTree.end())
		return NULL;

	return iter->second;
}

} /* NResource */ } /* ProjectZ */
